<script setup lang="ts">
import {reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {Camera, Plus, X} from 'lucide-vue-next'
import TopNav from '@/components/TopNav.vue'
import {add} from "@/api/recipe";
import {ElMessage} from "element-plus";


const router = useRouter()
const imageInput = ref<HTMLInputElement>()
const isSubmitting = ref(false)

const form = reactive<AddRecipeForm>({
  title: '',
  description: '',
  imageUrl: '',
  cookTime: 30,
  servings: 2,
  difficulty: 'easy',
  ingredients: [{name: '', amount: ''}],
  steps: [{stepOrder: 1, description: '', image: ''}]
})

const handleImageUpload = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      form.image = e.target?.result as string
    }
    reader.readAsDataURL(file)
  }
}

const triggerImageUpload = () => {
  imageInput.value?.click()
}

const handleStepImageUpload = (index: number, event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      form.steps[index].image = e.target?.result as string
    }
    reader.readAsDataURL(file)
  }
}

const triggerStepImageUpload = (index: number) => {
  const input = document.querySelector(`input[ref="stepImageInput${index}"]`) as HTMLInputElement
  input?.click()
}

// ----------------------------食谱食材操作----------------------------
const {addIngredient, removeIngredient} = ingredientOpr();

function ingredientOpr() {
  const addIngredient = () => {
    form.ingredients.push({name: '', amount: ''})
  }

  const removeIngredient = (index: number) => {
    if (form.ingredients.length > 1) {
      form.ingredients.splice(index, 1)
    }
  }
  return {addIngredient, removeIngredient};
}

// ----------------------------制作步骤操作----------------------------
const {addStep, removeStep} = stepOpr();

function stepOpr() {
  const addStep = () => {
    form.steps.push({stepOrder: form.steps.length + 1, description: '', image: ''})
  }

  const removeStep = (index: number) => {
    if (form.steps.length > 1) {
      form.steps.splice(index, 1)
    }
  }
  return {addStep, removeStep};
}

// ----------------------------上传食谱----------------------------
const handleSubmit = async () => {
  isSubmitting.value = true

  // 验证表单
  if (!form.title.trim()) {
    ElMessage.error('请输入菜名')
    isSubmitting.value = false
    return
  }

  if (!form.cookTime || form.cookTime <= 0) {
    ElMessage.error('请输入有效的烹饪时间')
    isSubmitting.value = false
    return
  }

  if (!form.servings || form.servings <= 0) {
    ElMessage.error('请输入有效的份量')
    isSubmitting.value = false
    return
  }

  // 过滤空的材料
  const validIngredients = form.ingredients.filter(ing => ing.name.trim() && ing.amount.trim())
  if (validIngredients.length === 0) {
    ElMessage.error('请至少添加一个材料')
    isSubmitting.value = false
    return
  }

  // 过滤空的步骤
  const validSteps = form.steps.filter(step => step.description.trim())
  if (validSteps.length === 0) {
    ElMessage.error('请至少添加一个制作步骤')
    isSubmitting.value = false
    return
  }

  const result: any = await add(form);
  if (result.code !== 200) {
    ElMessage.error('保存失败，请重试')
    isSubmitting.value = false
    return
  }
  ElMessage.success('食谱保存成功！')
  await router.push('/')
  isSubmitting.value = false
}

const handleCancel = () => {
  if (confirm('确定要取消吗？未保存的内容将丢失。')) {
    router.back()
  }
}
</script>
<template>
  <div class="add-recipe-page">
    <TopNav title="添加食谱" :show-back="true"/>

    <main class="main-content">
      <form @submit.prevent="handleSubmit" class="recipe-form">
        <!-- 基本信息 -->
        <section class="form-section">
          <h2 class="section-title">基本信息</h2>

          <div class="form-group">
            <label class="form-label">菜名 *</label>
            <input
                v-model="form.title"
                type="text"
                class="form-input"
                placeholder="请输入菜名"
                required
            />
          </div>

          <div class="form-group">
            <label class="form-label">描述</label>
            <textarea
                v-model="form.description"
                class="form-textarea"
                placeholder="简单描述这道菜的特点"
                rows="3"
            ></textarea>
          </div>

          <div class="form-group">
            <label class="form-label">菜品图片</label>
            <div class="image-upload">
              <input
                  ref="imageInput"
                  type="file"
                  accept="image/*"
                  @change="handleImageUpload"
                  class="image-input"
              />
              <div class="upload-area" @click="triggerImageUpload">
                <img v-if="form.image" :src="form.image" alt="菜品图片" class="preview-image"/>
                <div v-else class="upload-placeholder">
                  <Camera :size="32"/>
                  <p>点击上传图片</p>
                </div>
              </div>
            </div>
          </div>
        </section>

        <!-- 烹饪信息 -->
        <section class="form-section">
          <h2 class="section-title">烹饪信息</h2>

          <div class="form-row">
            <div class="form-group">
              <label class="form-label">烹饪时间（分钟）*</label>
              <input
                  v-model.number="form.cookTime"
                  type="number"
                  class="form-input"
                  placeholder="30"
                  required
              />
            </div>

            <div class="form-group">
              <label class="form-label">份量（人份）*</label>
              <input
                  v-model.number="form.servings"
                  type="number"
                  class="form-input"
                  placeholder="2"
                  required
              />
            </div>
          </div>

          <div class="form-group">
            <label class="form-label">难度等级</label>
            <select v-model="form.difficulty" class="form-select">
              <option value="easy">简单</option>
              <option value="medium">中等</option>
              <option value="hard">困难</option>
            </select>
          </div>
        </section>

        <!-- 材料清单 -->
        <section class="form-section">
          <h2 class="section-title">材料清单</h2>

          <div class="ingredients-list">
            <div
                v-for="(ingredient, index) in form.ingredients"
                :key="index"
                class="ingredient-item"
            >
              <input
                  v-model="ingredient.name"
                  type="text"
                  class="form-input"
                  placeholder="材料名称"
              />
              <input
                  v-model="ingredient.amount"
                  type="text"
                  class="form-input"
                  placeholder="用量"
              />
              <button
                  type="button"
                  @click="removeIngredient(index)"
                  class="remove-btn"
              >
                <X :size="20"/>
              </button>
            </div>
          </div>

          <button
              type="button"
              @click="addIngredient"
              class="btn btn-outline add-ingredient-btn"
          >
            <Plus :size="20"/>
            添加材料
          </button>
        </section>

        <!-- 制作步骤 -->
        <section class="form-section">
          <h2 class="section-title">制作步骤</h2>

          <div class="steps-list">
            <div
                v-for="(step, index) in form.steps"
                :key="index"
                class="step-item"
            >
              <div class="step-number">{{ index + 1 }}</div>
              <div class="step-content">
                <textarea
                    v-model="step.description"
                    class="form-textarea"
                    placeholder="详细描述制作步骤"
                    rows="3"
                ></textarea>
                <div class="step-image-upload">
                  <input
                      :ref="`stepImageInput${index}`"
                      type="file"
                      accept="image/*"
                      @change="handleStepImageUpload(index, $event)"
                      class="image-input"
                  />
                  <div class="upload-area" @click="triggerStepImageUpload(index)">
                    <img v-if="step.image" :src="step.image" alt="步骤图片" class="preview-image"/>
                    <div v-else class="upload-placeholder">
                      <Camera :size="20"/>
                      <span>添加图片</span>
                    </div>
                  </div>
                </div>
              </div>
              <button
                  type="button"
                  @click="removeStep(index)"
                  class="remove-btn"
              >
                <X :size="20"/>
              </button>
            </div>
          </div>

          <button
              type="button"
              @click="addStep"
              class="btn btn-outline add-step-btn"
          >
            <Plus :size="20"/>
            添加步骤
          </button>
        </section>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <button type="button" @click="handleCancel" class="btn btn-outline">
            取消
          </button>
          <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
            <div v-if="isSubmitting" class="loading"></div>
            {{ isSubmitting ? '保存中...' : '保存食谱' }}
          </button>
        </div>
      </form>
    </main>
  </div>
</template>
<style lang="scss" scoped>
.add-recipe-page {
  min-height: 100vh;
  background-color: var(--color-background);
}

.main-content {
  max-width: 800px;
  margin: 0 auto;
  padding: var(--spacing-md);
}

.recipe-form {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
}

.form-section {
  background-color: var(--color-surface);
  padding: var(--spacing-lg);
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
}

.section-title {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--color-text);
  margin-bottom: var(--spacing-lg);
  padding-bottom: var(--spacing-sm);
  border-bottom: 2px solid var(--color-primary);
}

.form-group {
  margin-bottom: var(--spacing-lg);
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: var(--spacing-md);
}

.form-label {
  display: block;
  font-weight: 500;
  color: var(--color-text);
  margin-bottom: var(--spacing-xs);
}

.form-input,
.form-textarea,
.form-select {
  width: 100%;
  padding: var(--spacing-sm) var(--spacing-md);
  border: 2px solid var(--color-border);
  border-radius: var(--radius-md);
  font-size: var(--font-size-md);
  transition: border-color 0.3s ease;

  &:focus {
    outline: none;
    border-color: var(--color-primary);
  }

  &::placeholder {
    color: var(--color-text-light);
  }
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.image-upload {
  margin-top: var(--spacing-sm);
}

.image-input {
  display: none;
}

.upload-area {
  width: 100%;
  height: 200px;
  border: 2px dashed var(--color-border);
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    border-color: var(--color-primary);
    background-color: rgba(255, 107, 53, 0.05);
  }
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: var(--radius-md);
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: var(--color-text-light);

  p {
    margin-top: var(--spacing-xs);
    font-size: var(--font-size-sm);
  }
}

.ingredients-list,
.steps-list {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
}

.ingredient-item {
  display: grid;
  grid-template-columns: 1fr 1fr auto;
  gap: var(--spacing-sm);
  align-items: center;
}

.step-item {
  display: flex;
  gap: var(--spacing-md);
  align-items: flex-start;
}

.step-number {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  background-color: var(--color-primary);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: var(--font-size-lg);
}

.step-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.step-image-upload {
  .upload-area {
    height: 120px;
  }
}

.remove-btn {
  width: 40px;
  height: 40px;
  border: none;
  background-color: var(--color-error);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background-color: #c0392b;
    transform: scale(1.1);
  }
}

.add-ingredient-btn,
.add-step-btn {
  width: 100%;
  justify-content: center;
  gap: var(--spacing-sm);
}

.form-actions {
  display: flex;
  gap: var(--spacing-md);
  justify-content: center;
  padding: var(--spacing-lg);

  .btn {
    min-width: 120px;
  }
}

@media (max-width: 768px) {
  .form-row {
    grid-template-columns: 1fr;
  }

  .ingredient-item {
    grid-template-columns: 1fr;
    gap: var(--spacing-sm);
  }

  .step-item {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .step-content {
    width: 100%;
  }

  .form-actions {
    flex-direction: column;

    .btn {
      width: 100%;
    }
  }
}
</style>
